//! # 指标收集系统模块
//!
//! 提供详细的性能指标收集、聚合和分析功能
//!
//! 支持功能：
//! - 多维度指标收集（计数器、直方图、仪表盘）
//! - 指标标签和分组
//! - 时间序列数据存储
//! - 指标聚合和统计分析
//! - 自定义指标类型

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::sync::atomic::{AtomicU64, AtomicI64, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::RwLock;

// 为了向后兼容，创建类型别名
type ObservabilityResult<T> = Result<T, crate::ObservabilityError>;

/// 指标类型
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MetricType {
    /// 计数器 - 只增不减的累积指标
    Counter,
    /// 仪表盘 - 可增可减的瞬时值
    Gauge,
    /// 直方图 - 观察值的分布
    Histogram,
    /// 摘要 - 观察值的统计摘要
    Summary,
}

/// 指标值
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MetricValue {
    /// 计数器值
    Counter(u64),
    /// 仪表盘值
    Gauge(f64),
    /// 直方图值
    Histogram(HistogramValue),
    /// 摘要值
    Summary(SummaryValue),
}

/// 直方图值
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistogramValue {
    /// 桶边界和计数
    pub buckets: HashMap<String, u64>,
    /// 总计数
    pub count: u64,
    /// 总和
    pub sum: f64,
}

/// 摘要值
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SummaryValue {
    /// 分位数
    pub quantiles: HashMap<String, f64>,
    /// 总计数
    pub count: u64,
    /// 总和
    pub sum: f64,
}

/// 指标标签
pub type Labels = HashMap<String, String>;

/// 指标元数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricMetadata {
    /// 指标名称
    pub name: String,
    /// 指标类型
    pub metric_type: MetricType,
    /// 帮助信息
    pub help: String,
    /// 单位
    pub unit: Option<String>,
}

/// 指标样本
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricSample {
    /// 指标元数据
    pub metadata: MetricMetadata,
    /// 标签
    pub labels: Labels,
    /// 指标值
    pub value: MetricValue,
    /// 时间戳 (Unix 毫秒)
    pub timestamp: u64,
}

/// 指标收集器接口
#[async_trait]
pub trait MetricCollector: Send + Sync {
    /// 收集指标
    async fn collect(&self) -> crate::ObservabilityResult<Vec<MetricSample>>;
    
    /// 获取收集器名称
    fn name(&self) -> &str;
}

/// 指标注册表
pub struct MetricRegistry {
    /// 已注册的指标
    metrics: Arc<RwLock<HashMap<String, Arc<dyn Metric>>>>,
    /// 收集器
    collectors: Arc<RwLock<Vec<Box<dyn MetricCollector>>>>,
}

impl MetricRegistry {
    /// 创建新的指标注册表
    pub fn new() -> Self {
        Self {
            metrics: Arc::new(RwLock::new(HashMap::new())),
            collectors: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// 注册指标
    pub async fn register_metric(&self, name: String, metric: Arc<dyn Metric>) -> crate::ObservabilityResult<()> {
        let mut metrics = self.metrics.write().await;
        if metrics.contains_key(&name) {
            return Err(crate::ObservabilityError::metrics_error(&format!("指标已存在: {}", name)));
        }
        metrics.insert(name, metric);
        Ok(())
    }

    /// 注册收集器
    pub async fn register_collector(&self, collector: Box<dyn MetricCollector>) {
        let mut collectors = self.collectors.write().await;
        collectors.push(collector);
    }

    /// 获取指标
    pub async fn get_metric(&self, name: &str) -> Option<Arc<dyn Metric>> {
        let metrics = self.metrics.read().await;
        metrics.get(name).cloned()
    }

    /// 收集所有指标
    pub async fn collect_all(&self) -> crate::ObservabilityResult<Vec<MetricSample>> {
        let mut samples = Vec::new();
        
        // 收集注册的指标
        {
            let metrics = self.metrics.read().await;
            for (name, metric) in metrics.iter() {
                if let Ok(metric_samples) = metric.collect(name).await {
                    samples.extend(metric_samples);
                }
            }
        }
        
        // 收集器收集的指标
        {
            let collectors = self.collectors.read().await;
            for collector in collectors.iter() {
                if let Ok(collector_samples) = collector.collect().await {
                    samples.extend(collector_samples);
                }
            }
        }
        
        Ok(samples)
    }

    /// 清除所有指标
    pub async fn clear(&self) {
        self.metrics.write().await.clear();
        self.collectors.write().await.clear();
    }
}

impl Default for MetricRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// 指标接口
#[async_trait]
pub trait Metric: Send + Sync {
    /// 收集指标样本
    async fn collect(&self, name: &str) -> crate::ObservabilityResult<Vec<MetricSample>>;
    
    /// 获取指标类型
    fn metric_type(&self) -> MetricType;
    
    /// 重置指标
    async fn reset(&self);
}

/// 计数器指标
pub struct Counter {
    value: AtomicU64,
    labels: Labels,
    help: String,
}

impl Counter {
    /// 创建新的计数器
    pub fn new(help: String, labels: Labels) -> Self {
        Self {
            value: AtomicU64::new(0),
            labels,
            help,
        }
    }

    /// 增加计数
    pub fn inc(&self) -> u64 {
        self.add(1)
    }

    /// 增加指定值
    pub fn add(&self, value: u64) -> u64 {
        self.value.fetch_add(value, Ordering::Relaxed) + value
    }

    /// 获取当前值
    pub fn get(&self) -> u64 {
        self.value.load(Ordering::Relaxed)
    }
}

#[async_trait]
impl Metric for Counter {
    async fn collect(&self, name: &str) -> crate::ObservabilityResult<Vec<MetricSample>> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;

        Ok(vec![MetricSample {
            metadata: MetricMetadata {
                name: name.to_string(),
                metric_type: MetricType::Counter,
                help: self.help.clone(),
                unit: None,
            },
            labels: self.labels.clone(),
            value: MetricValue::Counter(self.get()),
            timestamp,
        }])
    }

    fn metric_type(&self) -> MetricType {
        MetricType::Counter
    }

    async fn reset(&self) {
        self.value.store(0, Ordering::Relaxed);
    }
}

/// 仪表盘指标
pub struct Gauge {
    value: Arc<parking_lot::RwLock<f64>>,
    labels: Labels,
    help: String,
}

impl Gauge {
    /// 创建新的仪表盘
    pub fn new(help: String, labels: Labels) -> Self {
        Self {
            value: Arc::new(parking_lot::RwLock::new(0.0)),
            labels,
            help,
        }
    }

    /// 设置值
    pub fn set(&self, value: f64) {
        *self.value.write() = value;
    }

    /// 增加值
    pub fn add(&self, value: f64) -> f64 {
        let mut current = self.value.write();
        *current += value;
        *current
    }

    /// 减少值
    pub fn sub(&self, value: f64) -> f64 {
        let mut current = self.value.write();
        *current -= value;
        *current
    }

    /// 获取当前值
    pub fn get(&self) -> f64 {
        *self.value.read()
    }
}

#[async_trait]
impl Metric for Gauge {
    async fn collect(&self, name: &str) -> crate::ObservabilityResult<Vec<MetricSample>> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;

        Ok(vec![MetricSample {
            metadata: MetricMetadata {
                name: name.to_string(),
                metric_type: MetricType::Gauge,
                help: self.help.clone(),
                unit: None,
            },
            labels: self.labels.clone(),
            value: MetricValue::Gauge(self.get()),
            timestamp,
        }])
    }

    fn metric_type(&self) -> MetricType {
        MetricType::Gauge
    }

    async fn reset(&self) {
        self.set(0.0);
    }
}

/// 直方图指标
pub struct Histogram {
    buckets: Arc<RwLock<HashMap<String, AtomicU64>>>,
    bucket_bounds: Vec<f64>,
    count: AtomicU64,
    sum: Arc<parking_lot::RwLock<f64>>,
    labels: Labels,
    help: String,
}

impl Histogram {
    /// 创建新的直方图
    pub fn new(help: String, labels: Labels, buckets: Vec<f64>) -> Self {
        let bucket_map: HashMap<String, AtomicU64> = buckets.iter()
            .map(|&b| (b.to_string(), AtomicU64::new(0)))
            .collect();

        Self {
            buckets: Arc::new(RwLock::new(bucket_map)),
            bucket_bounds: buckets,
            count: AtomicU64::new(0),
            sum: Arc::new(parking_lot::RwLock::new(0.0)),
            labels,
            help,
        }
    }

    /// 观察值
    pub async fn observe(&self, value: f64) {
        self.count.fetch_add(1, Ordering::Relaxed);
        
        {
            let mut sum = self.sum.write();
            *sum += value;
        }

        // 更新桶计数
        let buckets = self.buckets.read().await;
        for &bucket_bound in &self.bucket_bounds {
            if value <= bucket_bound {
                if let Some(count) = buckets.get(&bucket_bound.to_string()) {
                    count.fetch_add(1, Ordering::Relaxed);
                }
            }
        }
    }

    /// 获取统计信息
    pub async fn get_stats(&self) -> (u64, f64, HashMap<String, u64>) {
        let count = self.count.load(Ordering::Relaxed);
        let sum = *self.sum.read();
        
        let buckets = self.buckets.read().await;
        let bucket_counts = buckets.iter()
            .map(|(bound, count)| (bound.clone(), count.load(Ordering::Relaxed)))
            .collect();

        (count, sum, bucket_counts)
    }
}

#[async_trait]
impl Metric for Histogram {
    async fn collect(&self, name: &str) -> crate::ObservabilityResult<Vec<MetricSample>> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;

        let (count, sum, buckets) = self.get_stats().await;

        Ok(vec![MetricSample {
            metadata: MetricMetadata {
                name: name.to_string(),
                metric_type: MetricType::Histogram,
                help: self.help.clone(),
                unit: None,
            },
            labels: self.labels.clone(),
            value: MetricValue::Histogram(HistogramValue {
                buckets,
                count,
                sum,
            }),
            timestamp,
        }])
    }

    fn metric_type(&self) -> MetricType {
        MetricType::Histogram
    }

    async fn reset(&self) {
        self.count.store(0, Ordering::Relaxed);
        *self.sum.write() = 0.0;
        
        let buckets = self.buckets.read().await;
        for (_, count) in buckets.iter() {
            count.store(0, Ordering::Relaxed);
        }
    }
}

/// 摘要指标
pub struct Summary {
    observations: Arc<RwLock<Vec<f64>>>,
    count: AtomicU64,
    sum: Arc<parking_lot::RwLock<f64>>,
    quantiles: Vec<f64>,
    labels: Labels,
    help: String,
    max_age: Duration,
}

impl Summary {
    /// 创建新的摘要
    pub fn new(help: String, labels: Labels, quantiles: Vec<f64>, max_age: Duration) -> Self {
        Self {
            observations: Arc::new(RwLock::new(Vec::new())),
            count: AtomicU64::new(0),
            sum: Arc::new(parking_lot::RwLock::new(0.0)),
            quantiles,
            labels,
            help,
            max_age,
        }
    }

    /// 观察值
    pub async fn observe(&self, value: f64) {
        self.count.fetch_add(1, Ordering::Relaxed);
        
        {
            let mut sum = self.sum.write();
            *sum += value;
        }

        {
            let mut observations = self.observations.write().await;
            observations.push(value);
            
            // 限制观察值数量，避免内存无限增长
            if observations.len() > 10000 {
                observations.remove(0);
            }
        }
    }

    /// 计算分位数
    pub async fn calculate_quantiles(&self) -> HashMap<String, f64> {
        let observations = self.observations.read().await;
        if observations.is_empty() {
            return HashMap::new();
        }

        let mut sorted_observations = observations.clone();
        sorted_observations.sort_by(|a, b| a.partial_cmp(b).unwrap());

        self.quantiles.iter()
            .map(|&q| {
                let index = (q * (sorted_observations.len() - 1) as f64) as usize;
                (q.to_string(), sorted_observations[index])
            })
            .collect()
    }

    /// 获取统计信息
    pub async fn get_stats(&self) -> (u64, f64, HashMap<String, f64>) {
        let count = self.count.load(Ordering::Relaxed);
        let sum = *self.sum.read();
        let quantiles = self.calculate_quantiles().await;
        
        (count, sum, quantiles)
    }
}

#[async_trait]
impl Metric for Summary {
    async fn collect(&self, name: &str) -> crate::ObservabilityResult<Vec<MetricSample>> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;

        let (count, sum, quantiles) = self.get_stats().await;

        Ok(vec![MetricSample {
            metadata: MetricMetadata {
                name: name.to_string(),
                metric_type: MetricType::Summary,
                help: self.help.clone(),
                unit: None,
            },
            labels: self.labels.clone(),
            value: MetricValue::Summary(SummaryValue {
                quantiles,
                count,
                sum,
            }),
            timestamp,
        }])
    }

    fn metric_type(&self) -> MetricType {
        MetricType::Summary
    }

    async fn reset(&self) {
        self.count.store(0, Ordering::Relaxed);
        *self.sum.write() = 0.0;
        self.observations.write().await.clear();
    }
}

/// 系统指标收集器（重复定义！）
/// WARNING: 这是重复定义，应该使用 rustcloud-metrics 模块中的 SystemMetricsCollector
/// TODO: 移除此定义，使用 rustcloud-metrics::prometheus::SystemMetricsCollector
/// 
/// 注意：rustcloud-metrics 模块已经提供了完整的 SystemMetricsCollector 实现
/// 包括 PrometheusMetric trait 支持和系统指标收集功能
/// 
/// 推荐使用方式：
/// ```rust
/// use rustcloud_metrics::prometheus::SystemMetricsCollector;
/// let collector = SystemMetricsCollector::new();
/// ```
#[deprecated(note = "请使用 rustcloud-metrics::prometheus::SystemMetricsCollector")]
pub struct SystemMetricsCollector {
    name: String,
}

#[allow(deprecated)]
impl SystemMetricsCollector {
    pub fn new() -> Self {
        Self {
            name: "system".to_string(),
        }
    }
}

#[async_trait]
#[allow(deprecated)]
impl MetricCollector for SystemMetricsCollector {
    async fn collect(&self) -> crate::ObservabilityResult<Vec<MetricSample>> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;

        let mut samples = Vec::new();

        // CPU 使用率 - 模拟数据
        samples.push(MetricSample {
            metadata: MetricMetadata {
                name: "system_cpu_usage_percent".to_string(),
                metric_type: MetricType::Gauge,
                help: "系统 CPU 使用率".to_string(),
                unit: Some("percent".to_string()),
            },
            labels: HashMap::new(),
            value: MetricValue::Gauge(25.5),
            timestamp,
        });

        // 内存使用率 - 模拟数据
        samples.push(MetricSample {
            metadata: MetricMetadata {
                name: "system_memory_usage_percent".to_string(),
                metric_type: MetricType::Gauge,
                help: "系统内存使用率".to_string(),
                unit: Some("percent".to_string()),
            },
            labels: HashMap::new(),
            value: MetricValue::Gauge(62.3),
            timestamp,
        });

        // 磁盘使用率 - 模拟数据
        samples.push(MetricSample {
            metadata: MetricMetadata {
                name: "system_disk_usage_percent".to_string(),
                metric_type: MetricType::Gauge,
                help: "系统磁盘使用率".to_string(),
                unit: Some("percent".to_string()),
            },
            labels: {
                let mut labels = HashMap::new();
                labels.insert("device".to_string(), "/dev/sda1".to_string());
                labels
            },
            value: MetricValue::Gauge(45.8),
            timestamp,
        });

        Ok(samples)
    }

    fn name(&self) -> &str {
        &self.name
    }
}

#[allow(deprecated)]
impl Default for SystemMetricsCollector {
    fn default() -> Self {
        Self::new()
    }
}

/// 指标导出器接口
#[async_trait]
pub trait MetricExporter: Send + Sync {
    /// 导出指标
    async fn export(&self, samples: &[MetricSample]) -> crate::ObservabilityResult<()>;
    
    /// 获取导出器名称
    fn name(&self) -> &str;
}

/// Prometheus 格式导出器
pub struct PrometheusExporter {
    name: String,
}

impl PrometheusExporter {
    pub fn new() -> Self {
        Self {
            name: "prometheus".to_string(),
        }
    }

    /// 将指标样本转换为 Prometheus 格式
    pub fn format_samples(&self, samples: &[MetricSample]) -> String {
        let mut output = String::new();
        let mut current_family = String::new();

        for sample in samples {
            // 输出 HELP 和 TYPE 信息
            if current_family != sample.metadata.name {
                current_family = sample.metadata.name.clone();
                output.push_str(&format!("# HELP {} {}\n", current_family, sample.metadata.help));
                
                let metric_type = match sample.metadata.metric_type {
                    MetricType::Counter => "counter",
                    MetricType::Gauge => "gauge",
                    MetricType::Histogram => "histogram",
                    MetricType::Summary => "summary",
                };
                output.push_str(&format!("# TYPE {} {}\n", current_family, metric_type));
            }

            // 格式化标签
            let labels_str = if sample.labels.is_empty() {
                String::new()
            } else {
                let labels: Vec<String> = sample.labels.iter()
                    .map(|(k, v)| format!("{}=\"{}\"", k, v))
                    .collect();
                format!("{{{}}}", labels.join(","))
            };

            // 输出指标值
            match &sample.value {
                MetricValue::Counter(value) => {
                    output.push_str(&format!("{}{} {} {}\n", 
                        sample.metadata.name, labels_str, value, sample.timestamp));
                }
                MetricValue::Gauge(value) => {
                    output.push_str(&format!("{}{} {} {}\n", 
                        sample.metadata.name, labels_str, value, sample.timestamp));
                }
                MetricValue::Histogram(hist) => {
                    // 输出桶
                    for (bound, count) in &hist.buckets {
                        let mut bucket_labels = sample.labels.clone();
                        bucket_labels.insert("le".to_string(), bound.clone());
                        let bucket_labels_str = format!("{{{}}}", 
                            bucket_labels.iter()
                                .map(|(k, v)| format!("{}=\"{}\"", k, v))
                                .collect::<Vec<_>>()
                                .join(","));
                        output.push_str(&format!("{}_bucket{} {} {}\n", 
                            sample.metadata.name, bucket_labels_str, count, sample.timestamp));
                    }
                    
                    // 输出总计数和总和
                    output.push_str(&format!("{}_count{} {} {}\n", 
                        sample.metadata.name, labels_str, hist.count, sample.timestamp));
                    output.push_str(&format!("{}_sum{} {} {}\n", 
                        sample.metadata.name, labels_str, hist.sum, sample.timestamp));
                }
                MetricValue::Summary(summary) => {
                    // 输出分位数
                    for (quantile, value) in &summary.quantiles {
                        let mut quantile_labels = sample.labels.clone();
                        quantile_labels.insert("quantile".to_string(), quantile.to_string());
                        let quantile_labels_str = format!("{{{}}}", 
                            quantile_labels.iter()
                                .map(|(k, v)| format!("{}=\"{}\"", k, v))
                                .collect::<Vec<_>>()
                                .join(","));
                        output.push_str(&format!("{}{} {} {}\n", 
                            sample.metadata.name, quantile_labels_str, value, sample.timestamp));
                    }
                    
                    // 输出总计数和总和
                    output.push_str(&format!("{}_count{} {} {}\n", 
                        sample.metadata.name, labels_str, summary.count, sample.timestamp));
                    output.push_str(&format!("{}_sum{} {} {}\n", 
                        sample.metadata.name, labels_str, summary.sum, sample.timestamp));
                }
            }
        }

        output
    }
}

#[async_trait]
impl MetricExporter for PrometheusExporter {
    async fn export(&self, samples: &[MetricSample]) -> crate::ObservabilityResult<()> {
        let formatted = self.format_samples(samples);
        tracing::debug!("导出 Prometheus 格式指标:\n{}", formatted);
        Ok(())
    }

    fn name(&self) -> &str {
        &self.name
    }
}

impl Default for PrometheusExporter {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_counter() {
        let counter = Counter::new("测试计数器".to_string(), HashMap::new());
        
        assert_eq!(counter.get(), 0);
        assert_eq!(counter.inc(), 1);
        assert_eq!(counter.add(5), 6);
        assert_eq!(counter.get(), 6);
        
        let samples = counter.collect("test_counter").await.unwrap();
        assert_eq!(samples.len(), 1);
        assert_eq!(samples[0].metadata.metric_type, MetricType::Counter);
    }

    #[tokio::test]
    async fn test_gauge() {
        let gauge = Gauge::new("测试仪表盘".to_string(), HashMap::new());
        
        gauge.set(10.5);
        assert_eq!(gauge.get(), 10.5);
        
        gauge.add(5.2);
        assert_eq!(gauge.get(), 15.7);
        
        gauge.sub(3.1);
        assert!((gauge.get() - 12.6).abs() < f64::EPSILON);
        
        let samples = gauge.collect("test_gauge").await.unwrap();
        assert_eq!(samples.len(), 1);
        assert_eq!(samples[0].metadata.metric_type, MetricType::Gauge);
    }

    #[tokio::test]
    async fn test_histogram() {
        let buckets = vec![0.1, 0.5, 1.0, 5.0, 10.0];
        let histogram = Histogram::new("测试直方图".to_string(), HashMap::new(), buckets);
        
        histogram.observe(0.3).await;
        histogram.observe(2.1).await;
        histogram.observe(0.8).await;
        
        let (count, sum, bucket_counts) = histogram.get_stats().await;
        assert_eq!(count, 3);
        assert!((sum - 3.2).abs() < f64::EPSILON);
        
        // 检查桶计数
        assert_eq!(bucket_counts["0.5"], 1); // 0.3
        assert_eq!(bucket_counts["1"], 2); // 0.3, 0.8
        assert_eq!(bucket_counts["5"], 3); // 0.3, 0.8, 2.1
        
        let samples = histogram.collect("test_histogram").await.unwrap();
        assert_eq!(samples.len(), 1);
        assert_eq!(samples[0].metadata.metric_type, MetricType::Histogram);
    }

    #[tokio::test]
    async fn test_summary() {
        let quantiles = vec![0.5, 0.9, 0.95, 0.99];
        let summary = Summary::new(
            "测试摘要".to_string(), 
            HashMap::new(), 
            quantiles, 
            Duration::from_secs(300)
        );
        
        // 添加一些观察值
        for i in 1..=100 {
            summary.observe(i as f64).await;
        }
        
        let (count, sum, calculated_quantiles) = summary.get_stats().await;
        assert_eq!(count, 100);
        assert_eq!(sum, 5050.0); // 1+2+...+100 = 5050
        
        // 检查分位数
        assert!(calculated_quantiles.contains_key("0.5"));
        assert!(calculated_quantiles.contains_key("0.95"));
        
        let samples = summary.collect("test_summary").await.unwrap();
        assert_eq!(samples.len(), 1);
        assert_eq!(samples[0].metadata.metric_type, MetricType::Summary);
    }

    #[tokio::test]
    async fn test_metric_registry() {
        let registry = MetricRegistry::new();
        
        // 注册一个计数器
        let counter = Arc::new(Counter::new("测试计数器".to_string(), HashMap::new()));
        registry.register_metric("test_counter".to_string(), counter.clone()).await.unwrap();
        
        // 注册系统指标收集器
        let collector = Box::new(SystemMetricsCollector::new());
        registry.register_collector(collector).await;
        
        // 收集所有指标
        let samples = registry.collect_all().await.unwrap();
        assert!(samples.len() >= 4); // 至少有计数器 + 系统指标
    }

    #[tokio::test]
    async fn test_prometheus_exporter() {
        let exporter = PrometheusExporter::new();
        
        let sample = MetricSample {
            metadata: MetricMetadata {
                name: "test_counter".to_string(),
                metric_type: MetricType::Counter,
                help: "测试计数器".to_string(),
                unit: None,
            },
            labels: {
                let mut labels = HashMap::new();
                labels.insert("service".to_string(), "test".to_string());
                labels
            },
            value: MetricValue::Counter(42),
            timestamp: 1234567890000,
        };
        
        let formatted = exporter.format_samples(&[sample]);
        assert!(formatted.contains("# HELP test_counter 测试计数器"));
        assert!(formatted.contains("# TYPE test_counter counter"));
        assert!(formatted.contains("test_counter{service=\"test\"} 42 1234567890000"));
    }
}